package com.ksl.kinglockguard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.app.AlarmManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Looper;

import com.ksl.kinglockguard.activity.LockMainActivity;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.network.appupdate.AppUpdateFileUtil;
import com.ksl.kinglockguard.network.appupdate.AppUpdateService;
import com.ksl.kinglockguard.utils.DeleteSdCacheUtil;
import com.ksl.kinglockguard.utils.ErrorRecordUtil;
import com.lsk.open.core.MyLog;

public class LockApplication extends Application {
	private static LockApplication app;
	public static boolean FLAG_MAIN_OPENED = false;
	@Override
	public void onCreate() {
		super.onCreate();
		MyLog.setDebug(true);//todo 开启debug
		app = this;
		new Thread(new Runnable(){
			@Override
			public void run() {
				MyLog.i("LockApplication", "LockApplicatin onCreate()");
				long interval = System.currentTimeMillis()-SharePreferenceSdkData.getFirstStartUpload(getApplicationContext());
				if(Math.abs(interval)>60*1000){
					SharePreferenceSdkData.setFirstStartUpload(getApplicationContext(), System.currentTimeMillis()+60*1000);
					Constants.initFiles();
					MyLog.i("jyh1", "~~Constants.initFiles()~~~");
					Looper.prepare();
					NetworkTask.needQuestTotalFlag(getApplicationContext());
					checkRootUpdate();
					startAlarm(getApplicationContext());
					new DeleteSdCacheUtil().start();//进行sdacrd检测
					Looper.loop(); 
					MyLog.i("jyh", "~~~~~~~~~Application finished~~~~~~~~~~~");
				}
			}	
		}).start();
		ErrorRecordUtil.start(getApplicationContext());//增加错误日志上传 todo ydy
		
	}
	
	public static final long TIME_INTERVAL_ONE_WEEK = 7* 24 * 60* 60 * 1000;
	//public static final long TIME_INTERVAL_ONE_WEEK = 7 * 60* 60 * 1000;
	public static void startAlarm(Context context){
		
		long lastUpdateTime = SharePreferenceSdkData.getLastCheckUpdateTime(context);
		if(lastUpdateTime == 0){
			SharePreferenceSdkData.setLastCheckUpdateTime(context, System.currentTimeMillis());
		}
		
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		
		Intent appUpdateService = new Intent(context, AppUpdateService.class);
		appUpdateService.setAction("com.ksl.kinglockguard.appupdate");
		appUpdateService.putExtra("check_update", true);
		PendingIntent updatePendingIntent = PendingIntent.getService(
				context, 0, appUpdateService, 0);
		am.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + TIME_INTERVAL_ONE_WEEK,
				TIME_INTERVAL_ONE_WEEK, updatePendingIntent);
	}
	
	/**
	 * 判断缓存数据是否可读
	 * 
	 * @param cachefile
	 * @return
	 */
	public boolean isReadDataCache(String cachefile) {
		return readObject(cachefile) != null;
	}
	
	/**
	 * 判断缓存是否存在
	 * 
	 * @param cachefile
	 * @return
	 */
	private boolean isExistDataCache(String cachefile) {
		boolean exist = false;
		File data = getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}
	
	/**
	 * 保存对象
	 * 
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = openFileOutput(file, MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}
	
	/**
	 * 读取对象
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public Serializable readObject(String file) {
		if (!isExistDataCache(file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();
			// 反序列化失败 - 删除缓存文件
			if (e instanceof InvalidClassException) {
				File data = getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}
	
	private void checkRootUpdate() {
		int oldVersionCode = getOldVersionCode();
		MyLog.i("version", "CleanmasterApplication checkRootUpdate ----------------- oldVersionCode: " + oldVersionCode);
		if(oldVersionCode != -1){
			int currentVersionCode = getCurrentVersionCode();
			MyLog.i("version", "CleanmasterApplication checkRootUpdate ----------------- currentVersionCode: " + currentVersionCode);
			if(currentVersionCode > oldVersionCode){
//				showOpenApplicationNotification();
				deleteVersionCode();
				deleteRootUpdateFile();
			}
		}
	}

	public static final String UPDATE_APK="blueFlash.apk";
	public static final String END_APK="end.apk";
	private void deleteRootUpdateFile() {
		File end = new File(AppUpdateFileUtil.getRootUpdateAppPath()+"/"+END_APK);
		if(end.exists()){
			end.delete();
		}
		File update = new File(AppUpdateFileUtil.getRootUpdateAppPath()+"/"+UPDATE_APK);
		if(update.exists()){
			update.delete();
		}
		File file = new File(AppUpdateFileUtil.getRootUpdateAppPath());
		if(file.exists()){
			file.delete();
		}
	}
	
	/**
	 * 在状态栏显示通知, 用户点击后安装
	 */
	public static final int OPEN_APP_NOTIFICATION_ID = 123581;
	private void showOpenApplicationNotification() {
		MyLog.i("version", "CleanmasterApplication -----showOpenApplicationNotification-------------");
		NotificationManager notificationManager = (NotificationManager) this
				.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

		Notification notification = new Notification(
			R.drawable.lock_notify_icon, getString(R.string.lock_app_name),	
			System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL; // 表明在点击了通知栏中的"清除通知"后，此通知不清除，经常与FLAG_ONGOING_EVENT一起使用
		notification.defaults = Notification.DEFAULT_ALL;

		// 设置通知的事件消息
		CharSequence contentTitle = getString(R.string.lock_app_name); // 通知栏标题
		CharSequence contentText = getString(R.string.lock_update_notification_ready_to_open); // 通知栏内容

		Intent mainPager = new Intent(this,LockMainActivity.class);
		mainPager.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		
		PendingIntent contentItent = PendingIntent.getActivity(this, 0,
				mainPager, 0);
		notification.setLatestEventInfo(this, contentTitle, contentText,
				contentItent);

		notificationManager.notify(OPEN_APP_NOTIFICATION_ID, notification);
	}
	
	private void deleteVersionCode(){
		String vcodePath = AppUpdateFileUtil.getUpdateVersionDir();
		File vcodeFile = new File( vcodePath );
		MyLog.i("version", "CleanmasterApplication ---deleteVersionCode- ---vcodeFile: " + vcodeFile.getAbsolutePath());
		if (vcodeFile.exists()){
			MyLog.i("version", "CleanmasterApplication ---deleteVersionCode-----exists" );
			vcodeFile.delete();
		}
	}
	
	private int getCurrentVersionCode(){
		PackageInfo packageInfo;
		try {
			packageInfo = getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return -1;
	}
	
	/*
	 * 如果文件不存在,或者发生异常,则返回-1
	 */
	private int getOldVersionCode(){
		String vcodePath = AppUpdateFileUtil.getUpdateVersionDir();
		File vcodeFile = new File( vcodePath );
		MyLog.i("version", "CleanmasterApplication ---getOldVersionCode ---vcodeFile: " + vcodeFile);
		if( !vcodeFile.exists()){
			return -1;
		}
		FileInputStream input;
		try {
			input = new FileInputStream(vcodeFile);
			byte[] data = new byte[(int) vcodeFile.length()];
			int length = input.read(data);
			if(length != -1){
				String versionCode = new String(data);
				return Integer.parseInt(versionCode);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return -1;
		} catch (IOException e) {
			e.printStackTrace();
			return -1;
		}
		
		return -1;
	}

	public static Context getInstance() {
		return app;
	}

}
